import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import {
  getFriends,
  addFriend,
  getFriendshipRequests,
  handleFriendshipRequest,
  updateFriendRemark,
} from '../services/im-friendship'
import { useQuasar } from 'quasar'
import websocketService from '../services/websocket'
import { useChatStore } from '../stores/chat'
import { getUserChats, ImChat } from '../services/im-chat'
import { generateDefaultAvatar } from '../utils/avatar'
import { API_BASE_URL } from '@/config/env'
import { calculateFriendUnreadCount, hasFriendNewMessages } from '../utils/unread-messages'

export interface FriendsListProps {
  currentTargetId?: string | null
}

export interface FriendsListEmits {
  'select-friend': [friendId: string]
}

export function useFriendsList(
  props: FriendsListProps,
  emit: (event: any, ...args: any[]) => void
) {
  const $q = useQuasar()
  const chatStore = useChatStore()

  // 状态
  const friends = ref<any[]>([])
  const chats = ref<ImChat[]>([])
  const searchQuery = ref('')
  const showAddFriendDialog = ref(false)
  const newFriendId = ref('')
  const friendMessage = ref('')
  const addingFriend = ref(false)
  const showRequestsDialog = ref(false)
  const pendingRequests = ref<any[]>([])
  const processingRequest = ref<string | null>(null)
  const showRemarkDialog = ref(false)
  const remarkText = ref('')
  const currentFriend = ref<any>(null)
  const updatingRemark = ref(false)
  const showProfileDialog = ref(false)
  const profileUser = ref<any>(null)
  const loadingProfile = ref(false)

  // 计算属性
  const filteredFriends = computed(() => {
    if (!searchQuery.value) return friends.value
    const query = searchQuery.value.toLowerCase()
    return friends.value.filter(
      (f) => {
        const toId = f.to_id?.toLowerCase() || ''
        const remark = f.remark?.toLowerCase() || ''
        const userName = f.user?.name?.toLowerCase() || ''
        return toId.includes(query) || remark.includes(query) || userName.includes(query)
      }
    )
  })

  const pendingRequestsCount = computed(() => {
    return pendingRequests.value.length
  })

  // 加载聊天列表
  const loadChats = async () => {
    try {
      const loadedChats = await getUserChats()
      chats.value = loadedChats
    } catch (error: any) {
      console.error('加载聊天列表失败:', error)
    }
  }

  // 加载好友列表
  const loadFriends = async (forceRefresh: boolean = false) => {
    try {
      console.log('开始加载好友列表, forceRefresh:', forceRefresh)
      // forceRefresh 为 true 时，强制从服务器获取最新数据（不使用缓存）
      // getFriends(false) 表示不使用缓存，从服务器获取
      const loadedFriends = await getFriends(!forceRefresh)
      console.log('getFriends 返回的数据:', loadedFriends)
      console.log('好友数量:', loadedFriends.length)
      friends.value = loadedFriends
      console.log('friends.value 已设置:', friends.value.length, '个好友', forceRefresh ? '(强制刷新)' : '(使用缓存)')
      console.log('filteredFriends 计算结果:', filteredFriends.value.length, '个好友')
      // 不再主动查询在线状态，等待 WebSocket 推送
      
      // 加载聊天列表以获取未读消息数
      await loadChats()
    } catch (error: any) {
      console.error('加载好友列表失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '获取好友列表失败',
      })
    }
  }

  // 计算未读消息数（使用统一工具函数）
  const getUnreadCount = (friend: any): number => {
    // 查找与该好友相关的聊天记录（单聊，chat_type = 1）
    const currentUserId = chatStore.currentUserId
    const currentOpenId = localStorage.getItem('openId') || ''
    
    // 重要：单聊的 chat.to_id 是接收方的ID（当前用户），需要通过消息来反向匹配
    let chat = chats.value.find(c => {
      if (c.chat_type !== 1) return false
      const chatToId = String(c.to_id || '').trim()
      
      // 如果 chat.to_id 是当前用户，这个聊天记录可能是与好友的聊天
      if (chatToId === currentUserId || chatToId === currentOpenId) {
        const friendId = friend.to_id || friend.user?.open_id || friend.user?.name
        const hasMessageFromFriend = chatStore.messages.some(msg => {
          if (msg.chat_type !== 1) return false
          const msgFromId = String(msg.from_user_id || '').trim()
          const msgToId = String(msg.to_user_id || '').trim()
          const friendIdStr = String(friendId || '').trim()
          
          const isFromFriend = msgFromId === friendIdStr || 
                              msgFromId === friend.user?.open_id ||
                              msgFromId === friend.user?.name
          const isToCurrentUser = msgToId === currentUserId || 
                                 msgToId === currentOpenId
          
          return isFromFriend && isToCurrentUser
        })
        
        return hasMessageFromFriend
      }
      
      // 也尝试直接匹配（某些情况下 chat.to_id 可能是好友ID）
      const friendToId = String(friend.to_id || '').trim()
      const friendOpenId = String(friend.user?.open_id || '').trim()
      const friendName = String(friend.user?.name || '').trim()
      
      return chatToId === friendToId || 
             chatToId === friendOpenId || 
             chatToId === friendName
    })
    
    return calculateFriendUnreadCount(
      chatStore.messages,
      friend,
      chat
    )
  }

  // 检查是否有新消息（使用统一工具函数）
  const hasNewMessages = (friend: any): boolean => {
    const currentUserId = chatStore.currentUserId
    const currentOpenId = localStorage.getItem('openId') || ''
    
    // 查找与该好友相关的聊天记录
    const chat = chats.value.find(c => {
      if (c.chat_type !== 1) return false
      const chatToId = String(c.to_id || '').trim()
      
      if (chatToId === currentUserId || chatToId === currentOpenId) {
        const friendId = friend.to_id || friend.user?.open_id || friend.user?.name
        const hasMessageFromFriend = chatStore.messages.some(msg => {
          if (msg.chat_type !== 1) return false
          const msgFromId = String(msg.from_user_id || '').trim()
          const msgToId = String(msg.to_user_id || '').trim()
          const friendIdStr = String(friendId || '').trim()
          
          const isFromFriend = msgFromId === friendIdStr || 
                              msgFromId === friend.user?.open_id ||
                              msgFromId === friend.user?.name
          const isToCurrentUser = msgToId === currentUserId || 
                                 msgToId === currentOpenId
          
          return isFromFriend && isToCurrentUser
        })
        
        return hasMessageFromFriend
      }
      
      const friendToId = String(friend.to_id || '').trim()
      const friendOpenId = String(friend.user?.open_id || '').trim()
      const friendName = String(friend.user?.name || '').trim()
      
      return chatToId === friendToId || 
             chatToId === friendOpenId || 
             chatToId === friendName
    })
    
    return hasFriendNewMessages(
      chatStore.messages,
      friend,
      chat
    )
  }

  // 加载待处理的好友请求
  const loadPendingRequests = async () => {
    try {
      const requests = await getFriendshipRequests(0) // 0: 待处理
      // 调试：打印请求数据，检查是否包含用户信息
      console.log('好友请求数据:', requests)
      if (requests.length > 0) {
        console.log('第一个请求的详细信息:', JSON.stringify(requests[0], null, 2))
      }
      pendingRequests.value = requests
    } catch (error: any) {
      console.error('获取好友请求失败:', error)
    }
  }

  // 格式化时间
  const formatTime = (timestamp?: number) => {
    if (!timestamp) return ''
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)
    
    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString()
  }

  // 获取好友请求的头像 URL
  const getRequestAvatarUrl = (request: any): string => {
    const userId = request.from_id
    const userName = request.user?.name || request.from_id
    return generateDefaultAvatar(userId, userName, 64)
  }

  // 处理好友请求头像加载错误
  const handleRequestAvatarError = (event: Event, request: any) => {
    const img = event.target as HTMLImageElement
    if (img) {
      img.src = getRequestAvatarUrl(request)
    }
  }

  // 选择好友
  const selectFriend = (friendId: string) => {
    // 触发事件，让父组件处理
    emit('select-friend', friendId)
  }

  // 添加好友
  const handleAddFriend = async () => {
    if (!newFriendId.value.trim()) {
      $q.notify({
        type: 'warning',
        message: '请输入用户ID、Open ID或用户名',
      })
      return
    }

    addingFriend.value = true
    try {
      await addFriend({
        to_id: newFriendId.value.trim(),
        remark: undefined,
        add_source: 'search',
        message: friendMessage.value.trim() || undefined,
      })
      $q.notify({
        type: 'positive',
        message: '好友请求已发送，等待对方同意',
      })
      showAddFriendDialog.value = false
      newFriendId.value = ''
      friendMessage.value = ''
      await loadFriends()
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '发送好友请求失败',
      })
    } finally {
      addingFriend.value = false
    }
  }

  // 处理好友请求
  const handleRequest = async (requestId: string, approveStatus: number) => {
    processingRequest.value = requestId
    try {
      await handleFriendshipRequest(requestId, approveStatus)
      $q.notify({
        type: 'positive',
        message: approveStatus === 1 ? '已同意好友请求' : '已拒绝好友请求',
      })
      await loadPendingRequests()
      await loadFriends()
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '处理好友请求失败',
      })
    } finally {
      processingRequest.value = null
    }
  }

  // 监听 WebSocket 好友请求通知
  const handleFriendshipRequestNotification = (data: any) => {
    console.log('收到好友请求通知:', data)
    // 自动刷新好友请求列表
    loadPendingRequests()
    // 显示通知
    $q.notify({
      type: 'info',
      message: `收到来自 ${data.from_id} 的好友请求`,
      position: 'top',
      actions: [
        { label: '查看', handler: () => { showRequestsDialog.value = true } }
      ]
    })
  }

  // 处理菜单操作
  const handleMenuAction = async (action: string, friend: any) => {
    switch (action) {
      case 'view':
        await loadUserProfile(friend.to_id)
        showProfileDialog.value = true
        break
        
      case 'remark':
        currentFriend.value = friend
        remarkText.value = friend.remark || ''
        showRemarkDialog.value = true
        break
        
      case 'clearChat':
        $q.dialog({
          title: '确认清空',
          message: `确定要清空本地存储中与 ${friend.remark || friend.user?.name || friend.to_id} 的聊天记录吗？此操作只删除本地聊天记录，不可恢复。`,
          cancel: true,
          persistent: true,
        }).onOk(async () => {
          try {
            // 收集所有可能的用户标识符（用户名、open_id、snowflake_id、to_id等），确保能匹配所有相关消息
            const allIds = new Set<string>()
            
            // 添加所有可能的标识符
            if (friend.user?.name) {
              allIds.add(friend.user.name)
            }
            if (friend.to_id) {
              allIds.add(friend.to_id)
            }
            if (friend.user?.open_id) {
              allIds.add(friend.user.open_id)
            }
            if (friend.user?.snowflake_id) {
              allIds.add(String(friend.user.snowflake_id))
            }
            
            // 将 Set 转换为数组
            const targetIds = Array.from(allIds)
            
            if (targetIds.length === 0) {
              throw new Error('无法确定用户标识符')
            }
            
            // 使用第一个作为主标识符，其余作为备选
            const targetUserId = targetIds[0]
            const alternativeIds = targetIds.slice(1)
            
            console.log('清空聊天记录，使用的标识符:', {
              targetUserId,
              alternativeIds,
              friend: friend
            })
            
            // 清理前端本地存储
            const deletedCount = await chatStore.clearUserMessages(
              targetUserId, 
              alternativeIds.length > 0 ? alternativeIds : undefined
            )
            
            // 如果当前正在与该用户聊天，清空当前目标
            if (chatStore.currentTargetId === friend.to_id) {
              chatStore.setTarget('', 'User')
            }
            
            // 刷新好友列表（确保显示正常）
            await loadFriends(true)
            
            $q.notify({
              type: 'positive',
              message: `已清空 ${deletedCount} 条本地聊天记录`,
            })
          } catch (error: any) {
            console.error('清空聊天记录失败:', error)
            $q.notify({
              type: 'negative',
              message: error.message || '清空聊天记录失败',
            })
          }
        })
        break
        
      case 'delete':
        $q.dialog({
          title: '确认删除',
          message: `确定要删除好友 ${friend.remark || friend.to_id} 吗？`,
          cancel: true,
          persistent: true,
        }).onOk(async () => {
          try {
            const { removeFriend } = await import('../services/im-friendship')
            await removeFriend(friend.to_id)
            $q.notify({
              type: 'positive',
              message: '好友已删除',
            })
            await loadFriends()
          } catch (error: any) {
            $q.notify({
              type: 'negative',
              message: error.message || '删除好友失败',
            })
          }
        })
        break
        
      case 'black':
        const actionText = friend.black === 2 ? '取消拉黑' : '拉黑'
        $q.dialog({
          title: `确认${actionText}`,
          message: `确定要${actionText} ${friend.remark || friend.to_id} 吗？`,
          cancel: true,
          persistent: true,
        }).onOk(async () => {
          try {
            const { blackFriend } = await import('../services/im-friendship')
            await blackFriend(friend.to_id)
            $q.notify({
              type: 'positive',
              message: `${actionText}成功`,
            })
            await loadFriends()
          } catch (error: any) {
            $q.notify({
              type: 'negative',
              message: error.message || `${actionText}失败`,
            })
          }
        })
        break
    }
  }

  // 更新备注
  const handleUpdateRemark = async () => {
    if (!currentFriend.value) return
    
    updatingRemark.value = true
    try {
      await updateFriendRemark(currentFriend.value.to_id, remarkText.value.trim() || undefined)
      $q.notify({
        type: 'positive',
        message: '备注已更新',
      })
      showRemarkDialog.value = false
      await loadFriends()
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '更新备注失败',
      })
    } finally {
      updatingRemark.value = false
    }
  }

  // 加载用户资料
  const loadUserProfile = async (userId: string) => {
    loadingProfile.value = true
    profileUser.value = null
    try {
      const token = localStorage.getItem('token')
      const { API_BASE_URL } = await import('@/config/env')
      const response = await fetch(`${API_BASE_URL}/api/users/${encodeURIComponent(userId)}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      })
      
      if (response.ok) {
        profileUser.value = await response.json()
      } else {
        $q.notify({
          type: 'negative',
          message: '获取用户资料失败',
        })
      }
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '获取用户资料失败',
      })
    } finally {
      loadingProfile.value = false
    }
  }

  // 定期刷新定时器
  let refreshInterval: number | null = null
  let chatRefreshInterval: number | null = null

  // 监听请求对话框，打开时加载请求列表
  watch(showRequestsDialog, (newVal) => {
    if (newVal) {
      loadPendingRequests()
    }
  })

  // 添加一个响应式的更新触发器，用于强制更新未读消息显示
  const unreadUpdateTrigger = ref(0)
  
  // 监听消息变化，自动更新未读消息数
  watch(() => chatStore.messages, () => {
    // 当消息变化时，刷新聊天列表以更新未读消息数
    loadChats().catch(err => {
      console.error('刷新聊天列表失败:', err)
    })
    
    // 触发响应式更新
    unreadUpdateTrigger.value++
    
    // 添加调试：当消息变化时，检查好友的未读消息
    if (import.meta.env.DEV && friends.value.length > 0) {
      console.log('📬 消息变化，检查好友未读消息...', {
        totalMessages: chatStore.messages.length,
        singleChatMessages: chatStore.messages.filter(m => m.chat_type === 1).length,
        friendsCount: friends.value.length,
        receivedMessages: chatStore.messages.filter(m => m.isReceived && m.chat_type === 1).length,
      })
      
      // 检查前3个好友的未读消息（用于调试）
      friends.value.slice(0, 3).forEach(friend => {
        const unreadCount = getUnreadCount(friend)
        const hasNew = hasNewMessages(friend)
        if (unreadCount > 0 || hasNew) {
          console.log('🔔 发现未读消息:', {
            friendName: friend.remark || friend.user?.name || friend.to_id,
            unreadCount,
            hasNew,
          })
        }
      })
    }
  }, { deep: true })
  
  // 监听聊天列表变化，也触发更新
  watch(() => chats.value, () => {
    unreadUpdateTrigger.value++
  }, { deep: true })

  // 监听已读序列号更新事件，刷新聊天列表以更新未读消息数
  const handleReadSequenceUpdated = () => {
    console.log('📊 好友列表收到已读序列号更新事件，刷新聊天列表')
    loadChats().catch(err => {
      console.error('刷新聊天列表失败:', err)
    })
  }

  // 生命周期钩子
  onMounted(() => {
    // 加载好友列表
    loadFriends()
    // 加载待处理的好友请求
    loadPendingRequests()
    websocketService.on('friendship_request', handleFriendshipRequestNotification)
    // 定期刷新好友请求列表（每30秒）
    refreshInterval = window.setInterval(() => {
      if (showRequestsDialog.value) {
        loadPendingRequests()
      }
    }, 30000)
    // 定期刷新聊天列表以更新未读消息数（每10秒）
    chatRefreshInterval = window.setInterval(() => {
      loadChats()
    }, 10000)
    
    // 监听已读序列号更新事件
    window.addEventListener('readSequenceUpdated', handleReadSequenceUpdated)
    
    // 添加调试：组件挂载后，检查好友的未读消息
    if (import.meta.env.DEV) {
      setTimeout(() => {
        console.log('👥 好友列表组件已挂载，检查未读消息...', {
          friendsCount: friends.value.length,
          chatsCount: chats.value.length,
          totalMessages: chatStore.messages.length,
          singleChatMessages: chatStore.messages.filter(m => m.chat_type === 1).length,
        })
        
        // 检查所有好友的未读消息
        friends.value.forEach(friend => {
          const unreadCount = getUnreadCount(friend)
          const hasNew = hasNewMessages(friend)
          if (unreadCount > 0 || hasNew) {
            console.log('🔔 好友有未读消息:', {
              friendName: friend.remark || friend.user?.name || friend.to_id,
              unreadCount,
              hasNew,
            })
          }
        })
      }, 2000) // 延迟2秒，确保数据已加载
    }
  })

  onUnmounted(() => {
    if (refreshInterval !== null) {
      clearInterval(refreshInterval)
    }
    if (chatRefreshInterval !== null) {
      clearInterval(chatRefreshInterval)
    }
    websocketService.off('friendship_request', handleFriendshipRequestNotification)
    // 清理已读序列号更新事件监听器
    window.removeEventListener('readSequenceUpdated', handleReadSequenceUpdated)
  })

  return {
    // 状态
    friends,
    chats,
    searchQuery,
    showAddFriendDialog,
    newFriendId,
    friendMessage,
    addingFriend,
    showRequestsDialog,
    pendingRequests,
    processingRequest,
    showRemarkDialog,
    remarkText,
    currentFriend,
    updatingRemark,
    showProfileDialog,
    profileUser,
    loadingProfile,
    // 计算属性
    filteredFriends,
    pendingRequestsCount,
    // 方法
    loadFriends,
    loadChats,
    getUnreadCount,
    hasNewMessages,
    unreadUpdateTrigger,
    loadPendingRequests,
    formatTime,
    getRequestAvatarUrl,
    handleRequestAvatarError,
    selectFriend,
    handleAddFriend,
    handleRequest,
    handleMenuAction,
    handleUpdateRemark,
    loadUserProfile,
  }
}

